package com.cskaoyan.utils;

import com.mysql.jdbc.Driver;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 创建日期: 2022/02/23 11:24
 *
 * @author ciggar
 */
public class JDBCUtils2 {

    // volatile 1. 保证多线程的内存可见性  2. 禁止指令重排序
    static String url;
    static String username;
    static String password;

    static {

        // 读取配置文件
        try {
            Properties properties = new Properties();
            FileInputStream in = new FileInputStream("jdbc.properties");

            properties.load(in);


            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            System.out.println("读取配置文件成功！！ url:" + url + ",username:" + username);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;

        try {
            // 注册驱动
            DriverManager.registerDriver(new Driver());


            // 获取连接
            connection = DriverManager.getConnection(url,username,password);

        }catch (Exception ex){
            ex.printStackTrace();
        }

        return connection;

    }

    // 关闭资源
    public static void releaseResouce(ResultSet resultSet, Statement statement,Connection connection){
        try {
            // 由于Java虚拟机在执行代码的时候可能会指令重排，那么我们需要保证resultSet、statement、connection关闭的先后顺序
            try{
                if(resultSet != null) resultSet.close();
            }finally {
                try{
                    if(statement != null) statement.close();
                }finally {
                    if (connection != null) connection.close();
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
